package com.kuangqiyuan.yatzygame;

import com.kuangqiyuan.yatzygame.rule.AbstractRuleHandler;
import com.kuangqiyuan.yatzygame.rule.PairsRuleHandler;
import com.kuangqiyuan.yatzygame.rule.StraightRuleHandler;
import com.kuangqiyuan.yatzygame.rule.TwoPairesRuleHandler;

public class RuleManager {
  private AbstractRuleHandler handler;

  private Play play;

  public RuleManager() {
    PairsRuleHandler pairsRuleHandler = new PairsRuleHandler();
    TwoPairesRuleHandler twoPairesRuleHandler = new TwoPairesRuleHandler();
    StraightRuleHandler straightRuleHandler = new StraightRuleHandler();

    this.handler = pairsRuleHandler;
    pairsRuleHandler.setNextHandler(twoPairesRuleHandler);
    twoPairesRuleHandler.setNextHandler(straightRuleHandler);
    straightRuleHandler.setNextHandler(null);
  }

  private int countBaseScore() {
    int score = 0;
    int[] records = play.getRecords();

    for (int i: records) {
      score += i;
    }

    return score;
  }

  public int countScore(Play play) {
    this.play = play;
    int score = this.countBaseScore();

    System.out.println(String.format("base score is: %d", score));

    if (this.handler != null) {
      int extraScore = this.handler.handleRule(play);
      System.out.println(String.format("extra score is: %d", extraScore));

      score += extraScore;
    }

    return score;
  }
}
